//
//  RegistViewController.m
//  HeWeiZhiNeng
//
//  Created by 林建 on 17/12/3.
//  Copyright © 2017年 YanCeyMichael.github.io. All rights reserved.
//

#import "RegistViewController.h"
#import "RequestManager.h"
#import "RegistView.h"
@interface RegistViewController ()<RegistViewDelegate>
@property (nonatomic, strong)RegistView *registView;
@property (nonatomic, assign)NSInteger timeNumber;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, assign)BOOL AgreeDelegate;

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.AgreeDelegate = YES;
    [self setUpNavigation];
    self.timeNumber = 71;
    [self.view addSubview:self.registView];
    [self.registView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    UITapGestureRecognizer *timeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(timeAction)];
    [self.registView.timeLabel addGestureRecognizer:timeTap];
    // Do any additional setup after loading the view.
}

-(void)setUpNavigation{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = Color.theme;
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 addTarget:self action:@selector(leftBar1Clicked) forControlEvents:UIControlEventTouchUpInside];
    [btn1 setImage:[UIImage imageNamed:@"zhuce_fanhui"] forState:UIControlStateNormal];
    [btn1 sizeToFit];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:btn1];
    self.navigationItem.leftBarButtonItem = item1;
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 62, 20)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"注册";
    titleLabel.textColor = Color.fullBtnTitle;
    titleLabel.font = Common_Font(18);
    self.navigationItem.titleView = titleLabel ;
}

#pragma mark ----- 创建注册视图 -----
-(RegistView *)registView{
    if (!_registView) {
        _registView = [[RegistView alloc]init];
        _registView.delegate = self;
    }
    return _registView;
}

-(void)leftBar1Clicked{
    [self.rt_navigationController popViewControllerAnimated:YES];
}

#pragma mark ----- 数据请求·获取验证码 -----
-(void)requestDataWithDynamicCode{
//    NSMutableDictionary *pardic = [@{@"phone":self.registView.phoneView.OutPutTF.text}mutableCopy];
//    [RequestManager requestWithUrlStringForAFN:@"http://106.14.216.209:8088/api/v1/accounts/sendVerificationCode" parDic:pardic requestType:RequestPOST finish:^(NSData *data) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"d %@",dic);
//        
//    } error:^(NSError *error) {
//    }];
    [[NetWork sharedManager] sendMessageWithPhone:self.registView.phoneView.OutPutTF.text CallBack:^(DataResponse *response) {
        NSLog(@"----%@",response);
    }];
}

#pragma mark ----- 验证码点击事件 -----
-(void)timeAction{
    if (![self.registView.timeLabel.text containsString:@"重发"]) {
        if (![self validateMobile:self.registView.phoneView.OutPutTF.text]){
            [[SingleManager shareManager] creatPushView:103 VC:self msg:@""];
        } else {
            if ([SingleManager shareManager].NetworkStatus == YES) {
                [self requestDataWithDynamicCode];
            } else {
                self.networkView.alpha = 0.7;
                [self.view addSubview:self.networkView];
                [UIView animateWithDuration:2 animations:^{
                    self.networkView.alpha = 0;
                }];
            }
        }
    }
}

#pragma mark ----- 同意标签状态 -----
-(void)AgreeState:(BOOL)state{
    if (state) {
        self.registView.agreeView.image = [UIImage imageNamed:@"zhuce_tonyi_gou"];
    } else {
        self.registView.agreeView.image = [UIImage imageNamed:@"zhuce_tonyi_kuang"];
    }
}

#pragma mark - 计时
#pragma mark ----- 计时器 -----
-(NSTimer *)timer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(time) userInfo:nil repeats:YES];
    
    return _timer;
}

#pragma mark 倒计时
-(void)time{
    self.timeNumber--;
    if (self.timeNumber <= 0) {
        [_timer invalidate];
        //        Login_Phone = !Login_Phone;
        self.registView.timeLabel.text = @"重新发送";
        self.timeNumber = 71;
        return;
    }
    self.registView.timeLabel.text = [NSString stringWithFormat:@"重发（%ld）",_timeNumber];
    
}

#pragma mark ----- 头视图协议方法 -----
- (void)userChoose:(NSInteger)tag {
    switch (tag) {
        case 109:
            [self CompleteRegist];
            break;
        case 110:
            [self AgreeDelegateAction];
            break;
            
        default:
            break;
    }
}

#pragma mark ----- 完成注册 -----
-(void)CompleteRegist{
    if (self.registView.phoneView.OutPutTF.text.length == 0) {
        [[SingleManager shareManager] creatPushView:101 VC:self msg:@""];
    } else if (![self validateMobile:self.registView.phoneView.OutPutTF.text] && ![self isValidateEmail:self.registView.phoneView.OutPutTF.text]){
        [[SingleManager shareManager] creatPushView:102 VC:self msg:@""];
    } else {
        [[NetWork sharedManager] registerWithUserName:@"13758146836" userpwd:@"123456l" CallBack:^(DataResponse *response) {
            
        }];
    }
}

#pragma mark ----- 同意协议 -----
-(void)AgreeDelegateAction{
    self.AgreeDelegate = !self.AgreeDelegate;
    [self AgreeState:self.AgreeDelegate];
}

#pragma mark ----- 判断手机格式 -----
-(BOOL)validateMobile:(NSString *)phone{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"1[3|5|7|8|][0-9]{9}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}

#pragma mark ----- 邮箱地址的正则表达式 -----
- (BOOL)isValidateEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
